package com.fablesoft.projectdatacollect.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Base64;

/**
 * 加密工具类
 *
 * @author r00148802
 *
 */
public final class EncryptionUtil
{
    
    private EncryptionUtil()
    {
        
    }
    

    /**
     * sha256Encrypt
     * <功能详细描述>
     * @param source String
     * @return String
     * @see [类、类#方法、类#成员]
     */
    public static String sha256Encrypt(String source)
    {
        byte[] digested = digest(source, "SHA-256");
        return encodeWithBASE64(digested);
    }

    /**
     * MD5策略
     * <功能详细描述>
     * @param source String
     * @return String
     * @see [类、类#方法、类#成员]
     */
    public static String md5Encrypt(String source)
    {
        byte[] digested = digest(source, "MD5");
        StringBuilder builder = new StringBuilder();
        for (byte b : digested) {
                builder.append(Integer.toHexString((b >> 4) & 0xf));
                builder.append(Integer.toHexString(b & 0xf));
        } 
        return builder.toString();
        //return encodeWithBASE64(digested);
    }

    /**
     * 将指定字节数组以BASE64编码
     *
     * @param source 字节数组
     * @return String
     */
    public static String encodeWithBASE64(byte[] source)
    {
        if (source == null)
        {
            return null;
        }
        Base64 base64=new Base64();
        byte[] res = base64.encode(source);
        return new String(res);
    }

    /**
     * 根据指定算法对字符串进行摘要
     *
     * @param strSrc 源字符串
     * @param encName 算法名
     * @return 摘要
     */
    private static byte[] digest(String strSrc, String encName)
    {
        MessageDigest md = null;

        byte[] bt = strSrc.getBytes();
        try
        {
            md = MessageDigest.getInstance(encName);
        }
        catch (NoSuchAlgorithmException e)
        {
            Log4jUtil.e(e.toString());
            return null;
        }

        md.update(bt);
        return md.digest();
    }
}
